<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">新增任务</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                label: t('sys.configuration.edit'),
                tooltip: t('sys.configuration.edit'),
                onClick: handleEdit.bind(null, record),
              },
              {
                label: t('sys.script.details'),
                tooltip: t('sys.script.details'),
                onClick: handleView.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
    <phaseView @register="registerphaseView" />
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { taskChatAPI } from '@/api/demo/chat';
import { PageWrapper } from '@/components/Page';
import { useModal } from '@/components/Modal';
import phaseView from './phaseView.vue';
import AccountModal from './AccountModal.vue';
import { columns, searchFormSchema } from './account.data';
import { useGo } from '@/hooks/web/usePage';
import { useI18n } from "@/hooks/web/useI18n";

const { t } = useI18n();
defineOptions({ name: 'AccountManagement' });

const go = useGo();
const [registerModal, { openModal }] = useModal();
const [registerphaseView, { openModal: openphaseView }] = useModal();
const searchInfo = reactive<Recordable>({});
const total = ref(0);

const tableTitle = computed(() => `私信任务列表 ${t('sys.configuration.common')} ${total.value} ${t('sys.configuration.strip')}`);

const [registerTable, { reload, updateTableDataRecord }] = useTable({
  title: tableTitle,
  api: async (params) => {
    const result = (await taskChatAPI(params)) as { items: any[]; total: number };
    total.value = result.total;
    return result;
  },
  rowKey: 'id',
  columns,
  useSearchForm: false,
  showTableSetting: true,
  bordered: true,
  showIndexColumn: false,
  actionColumn: {
    width: 120,
    title: t('sys.configuration.action'),
    dataIndex: 'action',
  },
});

function handleCreate() {
  openModal(true, { isUpdate: false });
}

function handleEdit(record: Recordable) {
  openModal(true, { record, isUpdate: true });
}

function handleSuccess({ isUpdate, values }) {
  if (isUpdate) {
    updateTableDataRecord(values.id, values);
  } else {
    reload();
  }
}

function handleView(record: Recordable) {
  openphaseView(true, { record });
}
</script>
